<template>
  <div class="mainbody">
    <el-container>
        <el-header height="150px">
            <el-row>
                <el-col :span="4" text-align="right">
                    <div @click="goToLogin" v-if="this.$root.userName == null || this.$root.userName == ''">请登录</div>
                    <div v-if = " this.$root.userName != null && this.$root.userName != '' ">你好!&nbsp;&nbsp;&nbsp;&nbsp;{{this.nickName}}</div>
                    <div>&nbsp;</div>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="2"><div>&nbsp;</div></el-col>
                <el-col :span="6">
                    <div class="grid-left bg-purple">
                        <div style="position:relative;color: #ff6633;">
                            <div style="position: absolute;height:75px;width: 100%;line-height:120px;font-size:24px;font-weight: 600;">购物系统</div>
                            <div style="position: absolute;height:75px;width: 100%;line-height:10px;top:75px;font-size: 18px;font-weight: 500;">gouwuxitong</div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div>&nbsp;&nbsp;</div>
                </el-col>
                <el-col :span="6" >
                    <div class="grid-right bg-purple">
                        <div>
                            <el-form>
                                <el-form-item>
                                    <div style="position:relative;background-color:white;height: 38px; line-height: 38px;top:40px;border:1px solid #ff6633;border-radius:30px;border-width:2px;padding:3px">
                                    <el-row>
                                        <el-col :span="5">
                                            <el-select placeholder="宝贝" value=宝贝 >
                                                <el-option label="商铺" value="shangpu">
                                                </el-option>
                                                <el-option label="天猫" value="tianmao">
                                                </el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="15"><el-input v-model="searchVal"></el-input></el-col>
                                        <el-col :span="4">
                                            <el-button :round="true" type="warning" style="color:white;width: 70px; " @click="searchGoods">搜索</el-button>
                                        </el-col>
                                        </el-row>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </el-col>
                <el-col :span="2"><div>&nbsp;</div></el-col>
            </el-row>
        </el-header>
        <!-- 内容主题 -->
        <el-main style="height: 100%;">
            <el-row>
                <el-col :span="2">&nbsp;</el-col>
                 <!-- 大盒子 -->
                <el-col :span="20">
                    <div style="border-radius:30px;background: white;">
                        <!-- 购物车头 -->
                        <div class="main-header">
                            <el-row>
                                <el-col :span="5"><div>购物车（全部<b font-weight="200px">{{ checkedAllCount }}</b>）</div></el-col>
                                <el-col :span="10">&nbsp;</el-col>
                                <el-col :span="9">
                                    <div>
                                        <el-select v-model="value1" placeholder="请选择收货地址">
                                            <el-option
                                            v-for="item in options"
                                            :key="item.value"
                                            :label="item.address"
                                            :value="item.id">
                                            </el-option>
                                        </el-select>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="goodsCaption">
                            <el-col :span="2">
                                <el-checkbox style="left: 35px;"  v-model="isCheckedAll" @change="checkAllChange" >{{ isCheckedAll ? '取消全选' : '全选' }}</el-checkbox>
                            </el-col>
                            <el-col :span="10" style="left:-50px">&nbsp;商品信息</el-col>
                            <el-col :span="3">&nbsp;单价</el-col>
                            <el-col :span="2">&nbsp;数量</el-col>
                            <el-col :span="3">&nbsp;金额</el-col>
                            <el-col :span="3">&nbsp;操作</el-col>
                        </div>
                        <div>
                            <el-card v-for="(goods,index) in goodsListChecked" :key="index"  :body-style="{ padding: '50px' }">
                                <el-col :span="1">
                                    <el-checkbox :key="goods.id" v-model="checkedList[index]" @change="changeCheck(index)"></el-checkbox>
                                </el-col>
                                <!-- 图片 -->
                                <el-col :span="3">
                                    <div><img :src="goods.goodsImage" alt="" width="50px" height="50px">&nbsp;</div>
                                </el-col>
                                <!-- 商品名 -->
                                <el-col :span="3">
                                    <div>&nbsp;
                                        <a :href="goods.url">{{goods.goodsName}}</a>
                                    </div>
                                </el-col>
                                <!-- 描述 -->
                                <el-col :span="4">
                                    <div>&nbsp;
                                        {{goods.goodsDescription}}
                                    </div>
                                </el-col>
                                <!-- 单价 -->
                                <el-col :span="3">
                                    <div>&nbsp;
                                        {{goods.goodsPrice}}
                                    </div>
                                </el-col>
                                <!-- 数量 -->
                                <el-col :span="3">
                                    <el-input-number size="mini" v-model="goods.goodsCount" controls-position="right" @change="handleChange(goods)" :min="1" :max="goods.goodsInventoryCount"></el-input-number>
                                </el-col>
                                <el-col :span="3">
                                    <div>&nbsp;
                                        {{goods.goodsPrice * goods.goodsCount}}
                                    </div>
                                </el-col>
                                <el-col :span="4">
                                    <el-button @click="removeGoods(index)" type="text" size="small">删除</el-button>
                                    <el-button @click="purchaseGoods(goods,index)" type="text" size="small">购买</el-button>
                                </el-col>
                            </el-card>
                        </div>
                        <el-row class="main-footer">
                            <el-col :span="12">&nbsp;</el-col>
                            <el-col :span="12">
                                <div class="amount">已选商品{{ checkedCountItem }}件&nbsp;&nbsp;&nbsp;&nbsp;已选商品（不含运费）:
                                    <b style="color: #ff6633;">{{ allGoodsSum }}</b>
                                    <el-button :round="true" type="warning" style="color:white;width: 70px;" @click="Account(index)">结算</el-button>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                    
                </el-col>
                <el-col :span="2">&nbsp;</el-col>
            </el-row>
        </el-main>
        <el-footer>作者：咕嘟[gudoo]</el-footer>
    </el-container>
  </div>
</template>

<script>
import {login,userInfo,getGoodsById,deleteCartInfo,getCartInfoByUserName,addGoodsAddress,findGoodsAddress,searchGoodsByGoodsName } from "../ajax/get"
import {addGoodsOrder} from "../ajax/post"
import defaultValue from "../utils/defalutValue"
export default {
    name: "shoppingTrolley",
    // 只用于自定义属性,自定义属性要写在return{}的大括号
    data () {
        return {
            userName: "",  // 接收用户名
            passWord: "", // 密码
            nickName: "", // 昵称
            goodsName:"", //商品名称
            searchVal: "", // 搜索值
            goodsList: [], // 商品数据
            checkedAllCount:0,//购物车商品的数量
            checkedCountItem:0,//购物车勾选商品的数量
            isIndeterminate: true,
            allGoodsSum:0,
            goodsListChecked: [], // 商品数据+checked
            state:"",//收货地址
            allAddress:[],//全部收获地址
            timeout:null,
            goodsInventoryCount:1,
            options:[],//收获地址列表
            value1: '',//选择收货地址的多选项
            label: '地址1',
            index: 1,
            checkedList: [], // 保存单选框的选中状态
            isCheckedAll: false // 是否全选
        };
    },
    computed: {
    // 计算选中的单选框数量
        checkedCount() {
            return this.checkedList.filter(Boolean).length;
        }
    },
    watch: {
    // 监听选中的单选框数量变化，更新全选状态
        checkedCount() {
            this.isCheckedAll = this.checkedCount === this.goodsListChecked.length;
        }
    },
    methods: {
        goToLogin() {
            this.$router.push({
                path: '/shopLogin',
                query: {
                    path: 'shoppingTrolley'
                }
            })
        },
        // 搜索商品
        searchGoods() {
                let goodsName=this.searchVal;
                // this.goodsName=this.searchVal;
            searchGoodsByGoodsName(goodsName).then(res => {
                console.log("搜索商品:",res);
            })
        },
        // 查找用户信息
        findUserInfo(userName) {
            userInfo(userName).then(res => {
                console.log("用户信息:",res);
                this.nickName = res.data.data.nickName;
                this.userName = res.data.data.userName;
                //获取购物地址
                 findGoodsAddress(res.data.data.userName).then(adr =>{
                    console.log("获取的地址",adr);
                    this.options=adr.data.data;
                    console.log("获取的地址1",this.options);
                })
            })
            //获取购物车数据
            getCartInfoByUserName(userName).then(zxc =>{
                console.log("购物车数据：---",zxc)
                this.goodsList = zxc.data.data;
                this.checkedAllCount=this.goodsList.length; 
                this.goodsListChecked = this.goodsList.map(d=>({
                    ...d,
                    goodsInventoryCount:0, // 库存
                }))
                console.log("新的购物车数据：---",this.goodsListChecked)
                for (let i in this.goodsListChecked) {
                    this.checkedList.push(false)
                    getGoodsById(this.goodsListChecked[i].goodsId).then(goods=> {
                        this.goodsListChecked[i].goodsInventoryCount = goods.data.data.goodsInventoryCount;
                    })
                }
                // console.log("新的购物车商品数量：---",this.goodsListChecked[index].goodsCount)
            })
        },
        //删除购物车
        removeGoods(index) {
            console.log("---",index);
            deleteCartInfo(this.goodsListChecked[index].goodsId,sessionStorage.getItem("userName")).then(res =>{
                console.log("删除购物车",res);
                this.findUserInfo(sessionStorage.getItem("userName"));
            })
        },
        //购买数量
        handleChange(goods) {
            console.log("商品",goods);
            goods.goodsAllPrice = goods.goodsCount * goods.goodsPrice;
            console.log("总",this.goodsListChecked);
        },
        //查找商品信息
        findGoods(){
            searchGoodsByGoodsName(this.goodsName).then(res =>{
            console.log(res);
            let goodsInfor =res.data.data;
            console.log("获取的用户信息",this.goodsInfor)
            this.goodsmessage = [{
              goodsName:goodsInfor.goodsName,
              goodsDescription:goodsInfor.goodsDescription,
              goodsPrice:goodsInfor.goodsPrice,
              goodsInventoryCount:goodsInfor.goodsInventoryCount,
            }]
          })
        },
        // 全选/取消全选
        checkAllChange(checked){
            console.log("==",this.checkedList);
            this.checkedList = new Array(this.goodsListChecked.length).fill(checked);
            this.changeCheck();
        },
        //选择地址        
        Search(queryString,res){
            var results = queryString ? this.allAddress.filter(this.createStateFilter(queryString)) : this.allAddress;
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                res(results);
            }, 3000 * Math.random());
        },
        createStateFilter(queryString) {
            return (state) => {
                return (state.goodsAddress.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        handleSelect(item) {
            console.log(item);
        },

        //新增订单,购买单个商品
        purchaseGoods(goods,index){
            // console.log(goods,"单行购买商品",index);
            // console.log("是否选中",this.checkedList);
            if (this.checkedList[index]==false) {
                this.$message.error("商品:"+goods.goodsName+"未选中，不可购买!");
            }else{
                let obj = {
                "createTime": "",
                "goodsAddress": this.value1,
                "goodsBuyAllPrice": goods.goodsCount*goods.goodsPrice,
                "goodsBuyCount": goods.goodsCount,
                "goodsBuyPrice": goods.goodsPrice,
                "goodsId": goods.goodsId,
                "goodsStatus": 2,
                "id": 0,
                "updateTime": "",
                "userName": sessionStorage.getItem("userName")
                }
                addGoodsOrder(obj).then(res =>{
                    console.log("订单数据:",res);
                    this.$message.error(res.data.msg);
                })
                return;
            }
        },
        //结算
        Account() {
            for (let t in this.checkedList) {
                if (this.checkedList[t]==false) {
                    this.$message.error("未选中商品，不可购买!");
                }else{
                let obj = {
                    "createTime": "",
                    "goodsAddress": this.value1,
                    "goodsBuyAllPrice": this.goodsListChecked[t].goodsCount*this.goodsListChecked[t].goodsPrice,
                    "goodsBuyCount": this.goodsListChecked[t].goodsCount,
                    "goodsBuyPrice": this.goodsListChecked[t].goodsPrice,
                    "goodsId": this.goodsListChecked[t].goodsId,
                    "goodsStatus": 2,
                    "id": 0,
                    "updateTime": "",
                    "userName": sessionStorage.getItem("userName")
                    }
                    addGoodsOrder(obj).then(res =>{
                        console.log("订单数据:",res);
                        this.$message.error(res.data.msg);
                    })
                }
            }
        },
        // 变更选择
        changeCheck(index) {
            this.checkedCountItem = 0;
            let Sum = 0;
            this.allGoodsSum = 0;
            console.log("变更",this.checkedList,this.checkedList[index],"==",index);
            for (let t in this.checkedList) {
                console.log("选中数量",this.checkedCountItem,"==",t);
                if(this.checkedList[t]==true){
                    this.checkedCountItem++;
                    Sum = this.goodsListChecked[t].goodsPrice * this.goodsListChecked[t].goodsCount;
                    this.allGoodsSum = Sum + this.allGoodsSum;
                }
            }
        }
    },
    mounted() {
        // console.log("全局变量:",this.$root.userName);
        // this.getGoodsInfo();
        this.checkedList = new Array(this.goodsListChecked.length).fill(false);

    },
    created() {
        console.log("自定义数据:",this.goodsList);
        this.findUserInfo(sessionStorage.getItem("userName"));
    }
}
</script>

<style scoped>
@import "../assets/css/shoppingTrolley.css";
</style>